#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <errno.h>

#include <ijpege_common.h>
#ifdef DMALLOC
#include <imp/dmalloc.h>
#endif

int ijpege_update_fenc(ijpege_t *h, ijpege_frame_t *fenc, ijpege_pic_t *src)
{
	if ((src->img.i_csp < C_CSP_I420) || (src->img.i_csp > C_CSP_T420)) {
		ijpege_log(h, C_LOG_ERROR, "%s(%d):Invalid input colorspace:%d\n", __func__, __LINE__, src->img.i_csp);
		goto err_input_csp;
	}

	if (h->param.b_user_fenc && (h->param.i_csp != src->img.i_csp)) {
		ijpege_log(h, C_LOG_ERROR, "%s(%d):Invalid input colorspace:%d\n", __func__, __LINE__, src->img.i_csp);
		goto err_input_csp;
	}

	if ((src->img.i_stride[0] < C_ALIGN(h->param.i_width, 16)) || (src->img.i_stride[1] < C_ALIGN(h->param.i_width, 16) / 2)) {
		ijpege_log(h, C_LOG_ERROR, "invalidate input picture stride\n");
		goto err_input_stride;
	}

	if (src->img.i_csp != C_CSP_T420 && ((src->img.i_lines[0] < C_ALIGN(h->param.i_height, 16)) || (src->img.i_lines[1] < C_ALIGN(h->param.i_height, 16) / 2))) {
		ijpege_log(h, C_LOG_ERROR, "invalidate input picture lines\n");
		goto err_input_lines;
	}
	if (h->param.b_user_nalbuffer) {
		h->out.nal.p_payload = *(src->nals_buffer);
		h->out.p_bitstream = *(src->nals_buffer);
		h->out.i_bitstream = src->nals_buffer_size;
	}

	fenc->i_ql = src->i_ql;
	fenc->i_pic_struct = src->i_pic_struct;

	if((fenc->i_pic_struct < C_PIC_STRUCT_AUTO) || (fenc->i_pic_struct > C_PIC_STRUCT_TRIPLE)) {
		fenc->i_pic_struct = C_PIC_STRUCT_AUTO;
	}

	if (fenc->i_pic_struct == C_PIC_STRUCT_AUTO) {
		fenc->i_pic_struct = C_PIC_STRUCT_PROGRESSIVE;
	}

	if (h->param.b_user_fenc) {
		fenc->plane[0] = src->img.plane[0];
		fenc->plane[1] = src->img.plane[1];
		fenc->i_stride[0] = src->img.i_stride[0];
		fenc->i_stride[1] = src->img.i_stride[1];
		fenc->i_lines[0] = src->img.i_lines[0];
		fenc->i_lines[1] = src->img.i_lines[1];
	} else {
		h->mc.copy_frame[c_mc_type(fenc->i_csp, src->img.i_csp)](fenc->plane,
				fenc->i_stride, src->img.plane, (int *)src->img.i_stride,
				h->param.i_width, h->param.i_height);
	}

	return 0;

err_input_lines:
err_input_stride:
err_input_csp:
	return -1;
}
